package com.xcdh.ittools.provider;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.xcdh.commons.utils.EncryptUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * TisJdbcDataSourceProvider
 * Created by wjg on 2024/4/20.
 */
public class JdbcDataSourceProvider extends AbstractJdbcDataSourceProvider {
    private final static String GET_DS_SQL = "select * from tool_ds" ;
    private DataSourceProperty masterDataSource  ;
    public JdbcDataSourceProvider(DataSourceProperty masterDatasource) {
        super(masterDatasource.getUrl(), masterDatasource.getUsername(), masterDatasource.getPassword());
        this.masterDataSource = masterDatasource ;
    }

    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        Map<String, DataSourceProperty> dataSourcePropertiesMap = new HashMap<>() ;
        statement.execute(GET_DS_SQL);
        ResultSet resultSet = statement.getResultSet();
        while (resultSet.next()){
            DataSourceProperty dataSourceProperty = new DataSourceProperty() ;
            dataSourceProperty.setDriverClassName(resultSet.getString("driver_class")) ;
            dataSourceProperty.setUrl(resultSet.getString("ds_url")) ;
            String password = resultSet.getString("password");
            dataSourceProperty.setUsername(resultSet.getString("username")) ;
            String decodePwd = EncryptUtil.getInstance().DESdecode(password, resultSet.getString("username"));
            dataSourceProperty.setPassword(decodePwd) ;
            dataSourcePropertiesMap.put(resultSet.getString("ds_name") ,dataSourceProperty ) ;
        }
        dataSourcePropertiesMap.put("master" , masterDataSource) ;
        return dataSourcePropertiesMap;
    }
}
